import React, { useState, useEffect } from 'react';
import { Select, Tag } from 'antd'
import { getVideoTagList } from '@/api/video'
const { Option } = Select;
const Tager = props => {

  const [tagList, setTaglist] = useState([]); // 视频标签 列表内容
  const [tagIdList, settagIdList] = useState([]); // 添加视频标签 已选择的标签

  // 获取 视频标签
  const getTaglist = () => {
    return new Promise((resolve, reject) => {
      getVideoTagList({
        pageSize: 1000,
        pageNum: 1
      }).then((res) => {
        const { list } = res.data;
        setTaglist(list || [])
        resolve(list)
      }).catch(() => {
        reject()
      });
    })
  };

  useEffect(() => {
    getTaglist()
  }, [])
  useEffect(() => {
    settagIdList(props.tagIdList || [])
  }, [props.tagIdList])


  const handleChangeSelect = (value) => {
    settagIdList(value);
    props.onChangeTags && props.onChangeTags(value);
  };


  // const tagRender = tagList.map((v) => (<Tag color={v.color} key={v.id} label={v.name}>{v.name}</Tag>));
  const tagRender = (props) => {
    const { value, closable, onClose } = props;
    const tagSelect = tagList.find(v => v.id === value);
    if (!tagSelect) {
      return null;
    }
    return (
      <Tag color={tagSelect.color} closable={closable} onClose={onClose} style={{ marginRight: 3 }}>
        {tagSelect.name}
      </Tag>
    );
  }
  const options = tagList.map(v => (<Option key={v.id} value={v.id} label={v.name}><span style={{ color: v.color }}>{v.name}</span></Option>))

  return (
    <Select mode="multiple"
      placeholder="Tags select"
      value={tagIdList}
      allowClear
      showArrow
      optionFilterProp="label"
      optionLabelProp='value'
      onChange={handleChangeSelect}
      tagRender={tagRender} >
      {options}
    </Select>
  );

};

export default Tager;